<?php
include_once $_SERVER['DOCUMENT_ROOT']."/controller/connect.php";
include_once $_SERVER['DOCUMENT_ROOT']."/model/Action.php";
/**
 * Created by PhpStorm.
 * User: lwh
 * Date: 2017/7/21
 * Time: 10:40
 */
class ActionDAO{
    const FIELD_ID = "actionId";
    const FIELD_LOCATION_ID = "locationId";
    const FIELD_DURATION = "duration";
    const FIELD_TYPE = "actionType";

    public $conn;

    function __construct()
    {
        $this->conn = new db();
    }

    //插入行为
    public function insert($action){

    }

    //删除行为
    public function delete($actionId){

    }

    //查询行为
    public function query($actionId){
        $sql = "select * from locaction where ".self::FIELD_ID." = ".$actionId;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if($row){
            $action = $this->loadDataFromResult($row);
            return $action;
        }
        else
            return null;
    }

    //更新行为
    public function update($action){

    }

    //根据location查询action列表
    public function queryActionListByLocation($locationId){
        $sql = "select * from locaction where ".self::FIELD_LOCATION_ID." = ".$locationId;
        $db = $this->conn->getDBConn();
        $rows = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if(count($rows) > 0){
            $actions = array();
            foreach ($rows as $row){
                $action = $this->loadDataFromResult($row);;
                array_push($actions,$action);
            }
            return $actions;
        }
        else
            return null;
    }

    //从结果集中构建出action对象
    private function loadDataFromResult($row){
        $action = new Action();
        $action->setId($row[self::FIELD_ID]);
        $action->setLocationId($row[self::FIELD_LOCATION_ID]);
        $action->setDuration($row[self::FIELD_DURATION]);
        $action->setType($row[self::FIELD_TYPE]);
        return $action;
    }
}